'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url admin/pages/kh/video/getTX_videos 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			drama_id,
			_id,
			appid,
			_add_time
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		//获取该剧所有集数
		let tv_series_data = await vk.baseDao.select({
			dbName: "a_tv_series", // 表名
			getCount: false, // 是否需要同时查询满足条件的记录总数量，默认false
			getMain: true, // 是否只返回rows数据，默认false
			pageIndex: 1, // 当前第几页
			pageSize: -1, // 每页条数
			whereJson: { // 条件
				tv_id: _id
			},
			// 按_id降序 asc 升序 desc 降序 
			sortArr: [{
				name: "series",
				type: "asc"
			}],
		});
		//改版后的才分流
		let appid2 = "wxeecc3404641c6d6d";
		let appsecret2 = "55cbc07ba6d5e3d8a45a76466eb00360"
		if(_add_time>1695484817000) {
			if(appid.length>0) {
				//通过appid查询对应的appsecret,
				let app = await db.collection('a_appid').where({ appid: appid[0] }).get()
				if(app.data.length > 0){
					let tv_appid = app.data[0].tv_appid || "";
					if(tv_appid){
						let app2 = await db.collection('a_appid').where({ appid: tv_appid }).get()
						if(app2.data.length > 0){
							appid2 = tv_appid;
							appsecret2 = app2.data[0].appsecret;
						}
					}
				}
			}
		}
		let access_token = await vk.openapi.weixin.auth.getAccessToken({
			appid: appid2,
			appsecret: appsecret2
		});

		let media_list = []
		async function getMediaList(drama_id, offset) {
			let apiUrl =
				"https://api.weixin.qq.com/wxa/sec/vod/listmedia?access_token=" + access_token
			return await uniCloud.httpclient.request(apiUrl, {
				method: 'POST',
				data: {
					"drama_id": drama_id,
					"offset": offset,

				},
				contentType: 'json', // 指定以application/json发送data内的数据
				dataType: 'json' // 指定返回值为json格式，自动进行parse
			})
		}
		let offset = 0
		let maxOffSet = Math.ceil(tv_series_data.length / 100)
		for (var i = 0; i < maxOffSet; i++) {
			let tmp = await getMediaList(drama_id, offset)
			if (tmp.res.data.errcode == 40001) {
				res.code = 40001
				res.msg = "access_token_tengxun已过期,请等到下一个整点再操作"
				return res
			}
			media_list = media_list.concat(tmp.res.data.media_info_list)
			offset += 100

		}


		// 匹配name字段并获取匹配到的对象
		function findObjectByName(arr, name) {
			var foundObject = arr.find(obj => obj.name === name);
			return foundObject;
		}

		let regex = /(\d*)集/;
		if (media_list) {
			//处理从腾讯拉取的数据
			let filteredTv_data = media_list.map((item) => {
				var match = item.name.match(regex);
				console.log("========================================" + match);
				if (match) {
					var episodeNumber = parseInt(match[1]); // 提取第一个捕获组中的数字
					item.name = Number(episodeNumber)
					console.log(episodeNumber); // 输出结果为 1
				} else {
					console.log("未找到匹配的数字");
				}
				return item
			});
			// res.txchuli_shuju = filteredTv_data
			// console.log("filteredTv_data[0].name-----------" + filteredTv_data[0].name + "类型为" +
			// 	typeof filteredTv_data[0].name);
			// console.log("filteredTv_data=====" + filteredTv_data[0].name);

			res.message = []
			//开始匹配
			let new_tv_data = tv_series_data.map((item, index) => {
				let result = {}
				console.log("===================81" + filteredTv_data[0].name);
				result = findObjectByName(filteredTv_data, item.series);
				console.log("result================82：" + result);
				if (result) {
					//匹配成功，进行替换
					console.log("================================85result.media_id" + result.media_id);
					item.media_id = result.media_id

				} else {
					//匹配不成功，返回错误信息
					console.log("================90" + result);
					res.message.push(`第${item.series}集匹配不成功,请检查该分集是否上传腾讯`)
					res.msg = res.msg + `第${item.series}集`
				}
				return item
			})
			// res.pipeihou_shuju = new_tv_data
			// console.log("new_tv_data========" + new_tv_data[0].series);


			//匹配完之后触发批量函数更新分集

			if (new_tv_data) {
				for (var i = 0; i < new_tv_data.length; i++) {
					let newInfo = await vk.baseDao.updateById({
						dbName: "a_tv_series",
						id: new_tv_data[i]._id,
						dataJson: {
							media_id: new_tv_data[i].media_id
						},
					});

				}

			}


		}




		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}